package com.gsn.common;

import java.util.Timer;
import java.util.TimerTask;

public class CheckTimeout extends Timer {
	public int lastSend = -1;
	public int count = 0;
	public static CheckTimeout instance;

	public interface ITimeoutListener {
		void onPing();

		void onTimeOut();
	}

	public ITimeoutListener listener;

	public CheckTimeout() {
		super();
		schedule(new CheckTask(), 0, 1000);

		instance = this;
	}

	public static CheckTimeout getInstance() {
		if (instance == null) {
			return new CheckTimeout();
		} else
			return instance;
	}

	class CheckTask extends TimerTask {

		@Override
		public void run() {
			// TODO Auto-generated method stub

			count++;
			//System.out.println(" count " + count + " " + lastSend);
			if (lastSend != -1 && count - lastSend > 5) {

				if (listener != null) {
					listener.onTimeOut();
				}
				lastSend = -1;
			} else {
				// on connect
				if (count > 100 && lastSend == -1) {
					count = 0;
				}

			}
		}

	}

	public void update() {
		lastSend = count;
		// System.out.println(" lastsend = " + lastSend);
	}

	public void resetLastSend() {
		lastSend = -1;
		// System.out.println("reset lastsend ");
	}

}
